<?php


namespace app\finance\controller;


use app\base\BaseController;
use think\Exception;
use think\facade\Db;
use think\facade\View;

class SaleRefundOrder extends BaseController
{
    protected $title='销售退款单';
    protected $table='money_order';
    protected $mType=2;

    public function index()
    {
        $param=$this->request->param();
        if (request()->isAjax()) {
            $where[]=['mo.status','>',-1];
            $where[]=['mo.type','=',$this->mType];

            if (isset($this->param['status'])&&$this->param['status']){
                $where[]=['mo.status','=',$this->param['status']];
            }
            if (isset($this->param['name'])&&$this->param['name']){
                $where[]=['py.name|py.code|ad.name|mo.orderNum','like','%'.$this->param['name'].'%'];
            }
            if (isset($this->param['orderDate'])&&$this->param['orderDate']){
                $dates=explode('~',$this->param['orderDate']);
                $where[]=['mo.orderDate','between',$dates];
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name($this->table)
                ->alias('mo')
                ->leftJoin('purveyor py','py.id=mo.purveyorId')
                ->leftJoin('admin ad','ad.id=mo.checkId')
                ->where($where)
                ->field("mo.*,py.name as pName,ad.name as payName,(select orderNum from fy_money_order mon where mon.id=mo.saveOrderId)saveOrderNum")
                ->order('mo.id DESC')
                ->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            return view();
        }
    }

    public function add()
    {
        $param=$this->param;
        $id=$param['id']??0;
        if ($this->request->post()){
            if (!$param['purveyorId']||!$param['saveOrderId']){
                return  to_assign(1,'参数缺失');
            }

            $param['update_time'] = time();
            if ($id){
                add_log('edit', $id, $this->param,$this->title);
            }else{
                unset($param['id']);
                $param['createId']=$this->uid;
                $param['orderNum']=dJBHBySql($this->table,'orderNum',getOrderPrefix($this->controller).date('Ymd'),false,1000);
                $param['type']=$this->mType;
                $param['departId']=$this->did;
                $param['create_time'] = time();
                add_log('add', $id, $this->param,$this->title);
            }
            try {
                Db::name($this->table)->save($param);
            }catch (\Exception $e){
                return to_assign(1,'操作失败：'.$e->getMessage());
            }
            return  to_assign();

        }else{
            $punList=Db::name('purveyor')->where('status',1)->where('dw_type',2)->field('id,name')->select();
            $detail=[];
            if ($id){
                $detail=Db::name($this->table)->where('id',$id)->find();
            }
            View::assign('punList',$punList);
            View::assign('detail',$detail);
            View::assign('id',$id);
            $bankList=Db::name('bank')->where('status',1)->column('name');
            View::assign('bankList',$bankList);
            return view('form');
        }
    }

    public function delete()
    {
        $ids=$this->param['id']??[];
        if (!$ids){
            return to_assign(1,'参数缺失');
        }
        $status=Db::name($this->table)->where('id','in',$ids)->column('status');
        if (in_array(2,$status)){
            return to_assign(1,'参数有误');
        }
        Db::startTrans();
        try {
            Db::name($this->table)->where('id','in',$ids)->update(['status'=>-1,'deleted'=>time()]);
            add_log('delete', $ids, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }

        return to_assign();
    }

    public function onSure()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $info=Db::name($this->table)->where('id',$id)->find();
        if (!$info||$info['status']!=1){
            return to_assign(1,'参数有误');
        }
        $conTractInfo=Db::name('sale_contract')
            ->where('orderNum',$info['contractOrder'])
            ->where('status',4)
            ->field("*,(select sum(money) from fy_money_order_contract_detail mo where mo.status=2 and type=1 and mo.contractOrder=fy_sale_contract.orderNum)receiptedMoney")
            ->find();
        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'checkId'=>$this->uid,
                'checkTime'=>date('Y-m-d H:i:s'),
                'status'=>2,
                'update_time'=>time()]);

            if ($conTractInfo){
                $conTractInfo['receiptedMoney']=$conTractInfo['receiptedMoney']?$conTractInfo['receiptedMoney']:0;
                if ($conTractInfo['receiptedMoney']<$info['money']){
                    throw new Exception('金额大于合同金额');
                }
//                if ($conTractInfo['unPay']==$info['money']){
//                    Db::name('sale_contract')->where('id',$conTractInfo['id'])
//                        ->update(['payStatus'=>3,'update_time'=>time()]);
//                }
//                if ($conTractInfo['unPay']>$info['money']){
//                    Db::name('sale_contract')->where('id',$conTractInfo['id'])
//                        ->update(['payStatus'=>2,'update_time'=>time()]);
//                }
                $recordData=[
                    'orderDate'=>$info['orderDate'],
                    'relatedOrderNum'=>$info['orderNum'],
                    'purveyorId'=>$info['purveyorId'],
                    'money'=>$info['money'],
                    'orderType'=>$this->mType,

                ];
                moneyRecord($recordData);
            }
            add_log('onSure', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }
    public function onCancel()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $info=Db::name($this->table)->where('id',$id)->find();
        if (!$info||$info['status']!=2){
            return to_assign(1,'参数有误');
        }
        $conTractInfo=Db::name('sale_contract')
            ->where('orderNum',$info['contractOrder'])
            ->where('status',4)
            ->field("*,(select sum(money) from fy_money_order_contract_detail mo where mo.status=2 and type=1 and mo.contractOrder=fy_sale_contract.orderNum)receiptedMoney")
            ->find();
        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'checkId'=>$this->uid,
                'checkTime'=>date('Y-m-d H:i:s'),
                'status'=>1,
                'update_time'=>time()]);


            if ($conTractInfo){
                $recordData=[
                    'orderDate'=>$info['orderDate'],
                    'relatedOrderNum'=>$info['orderNum'],
                    'purveyorId'=>$info['purveyorId'],
                    'money'=>$info['money'],
                    'mType'=>2,
                    'orderType'=>$this->mType,

                ];
                moneyRecord($recordData,true);
            }
            add_log('back', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }
}